import { Form, Select, DatePicker, TreeSelect } from 'antd';
import {
  SwapOutlined
} from '@ant-design/icons';
import { connect } from 'umi';
import React, { useEffect , useState } from 'react';
import moment from 'moment';
import styles from './index.less';
import classnames from 'classnames';
import { seqFormatterMonDate, formatterMon, selectModel, findTreeItem } from '@/utils/utils';

const { Option } = Select;
const { RangePicker } = DatePicker;
const HeaderFilter = (props) => {
  const { dispatch, params, fetchType = 'preSale', crowdStyle, needings, nameSpace, houseCommon, regionAble = '4' , needSwitch = true } = props
  const { purpose, staticts, date, dateRange, seqRange, currentDate, currentDates, region_code, currentSeqs, defaultDate, tabKey ,isShowDateRange } = needings
  const { regionGeo } = houseCommon;
  const [isDateRange , setIsDateRange] = useState(false)
  const [form] = Form.useForm();
  const { setFieldsValue } = form;

  useEffect(() => {
    // 每次点击tab，对过滤组件赋值
    setFieldsValue({
      purpose: checkOption(purpose, params.purpose, 'purpose'),
      staticts: checkOption(staticts, params.staticts, 'staticts'),
      date: checkDate(currentDate),
      dates: checkDate(currentDates)
    });
  }, [tabKey]);

  const layout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 20,
    },
  };

  /**
   * 检测下拉选项是否包含当前值
   * @param {string} option model参数值
   * @param {array} list 下拉框选项列表
   * @param {string} type 选择器名称
   */
  const checkOption = (option, list = [], type) => {
    if (list.includes(option)) {
      return option;
    } else {
      switch (type) {
        case 'purpose': {
          dispatch({
            type: selectModel(nameSpace, 'changePurpose'),
            payload: list.length && list[0]
          });
          break;
        }
        case 'staticts': {
          dispatch({
            type: selectModel(nameSpace, 'changeStaticts'),
            payload: list.length && list[0]
          });
          break;
        }
      }
    }
    return (list.length && list[0]) || '';
  };

  /**
   * 判断日期类型并使用moment处理
   * @param {*} value 日期值
   */
  const checkDate = (value) => {
    // [{
    //   "max_date": "2020-01-01",
    //   "seq": 1
    // },
    // {
    //   "max_date": "2020-02-01",
    //   "seq": 2
    // },]
    let date = null;

    if (Array.isArray(value)) {
      date = [moment(value[0]), moment(value[1])];
    } else if (Object.prototype.toString.call(value) === '[object Object]') {
      date = moment(value);
    } else if (typeof value == 'string') {
      date = moment(value);
    } else {
      date = moment(value);
    }



    return date
  }
  const dispatchFetch = type => {
    dispatch({
      type: selectModel(nameSpace, 'changeShowPic'),
      payload: false
    })
    dispatch({
      type: selectModel(nameSpace, 'fetchCommerBuildData'),
      payload: type
    });
  };

  // 下拉框选择处理
  const handChange = (value, type) => {
    switch (type) {
      case 'purpose': {
        dispatch({
          type: selectModel(nameSpace, 'changePurpose'),
          payload: value
        });
        dispatchFetch(fetchType);
        break;
      }
      case 'staticts': {
        dispatch({
          type: selectModel(nameSpace, 'changeStaticts'),
          payload: value
        });
        // dispatchFetch(fetchType)
        break;
      }
      case 'region': {
        const data = value
        const { value: code, label } = data
        const treeItem = findTreeItem(regionGeo, code, 'value')
        dispatch({
          type: selectModel(nameSpace, 'saveCurrentRegion'),
          payload: { name: label[0], adcode: code, level: treeItem.preadcode && treeItem.preadcode != '530000' ? 'district' : 'city' }
        });
        dispatchFetch(fetchType)
        break;
      }
      case 'date': {
        let date = value;
        let changedValue = {};
        const formatDate = formatterMon(date);
        // const strArr = date.split('-')
        // const strValue = strArr[0] + '年' + strArr[1] + '月'
        const seqValue = seqFormatterMonDate(date, dateRange, seqRange);
        changedValue.currentDate = formatDate;
        changedValue.currentSeq = seqValue;
        dispatch({
          type: selectModel(nameSpace, 'saveChangedDate'),
          payload: changedValue
        })
        dispatchFetch(fetchType)
        break
      }
      case 'dates': {
        let date = value;
        let changedValues = {};
        let seqValues = [];
        let formatDates = [];
        // const strArr = date.split('-')
        // const strValue = strArr[0] + '年' + strArr[1] + '月'
        date.map((item) => {
          seqValues.push(seqFormatterMonDate(item, dateRange, seqRange));
          formatDates.push(formatterMon(item));
        });
        changedValues.currentDates = formatDates;
        changedValues.currentSeqs = seqValues;

        dispatch({
          type: selectModel(nameSpace, 'saveChangedDates'),
          payload: changedValues
        })
        dispatchFetch(fetchType)
        break
      }
      default: {
        return false;
      }
    }
  };

  const disabledDate = (current) => {
    // return current && current < moment().endOf('day')
    return (
      current <= moment(defaultDate[0]).day(0) || current > moment(defaultDate[1]).endOf('day')
    );
  };
  const handleChangePick = () =>{
    const bolen = isShowDateRange
    dispatch({
      type: selectModel(nameSpace, 'changeIsShowDateRange'),
      payload: {isShowDateRange:!bolen}
    });
    dispatchFetch(fetchType)
  }

  const datePickRender = () =>{
    if(dateRange && tabKey == regionAble){
      return (
        <Form.Item name="dates" style={{marginRight:0}}>
              <RangePicker
                disabledDate={disabledDate}
                allowClear={false}
                picker="month"
                format="YYYY年MM月"
                onChange={(_, e) => handChange(e, 'dates')}
              />
        </Form.Item> 
      )
    }else{
      if(tabKey == '3'){
        return (
          <Form.Item name="date">
              <DatePicker
                disabledDate={disabledDate}
                allowClear={false}
                picker="month"
                type="r"
                format="YYYY年MM月"
                onChange={(_, e) => handChange(e, 'date')}
              />
            </Form.Item>
        )
      }else{
        if(isShowDateRange){
          return (
            <Form.Item name="dates" style={{marginRight:0}}>
              <RangePicker
                disabledDate={disabledDate}
                allowClear={false}
                picker="month"
                format="YYYY年MM月"
                onChange={(_, e) => handChange(e, 'dates')}
              />
            </Form.Item> 
          )
        }else{
          return (
            <Form.Item name="date">
              <DatePicker
                disabledDate={disabledDate}
                allowClear={false}
                picker="month"
                type="r"
                format="YYYY年MM月"
                onChange={(_, e) => handChange(e, 'date')}
              />
            </Form.Item>
          )
        }
      }
    }
  }
  return (
    <div
      className={classnames(
        styles.headerFilter,
        crowdStyle ? styles.headerFilter_left : styles.headerFilter_center,
      )}
    >
      <Form {...layout} name="basic" layout="inline" form={form}>
        <Form.Item name="purpose">
          {params.purpose && (
            <Select
              defaultValue={purpose || params.purpose[0]}
              style={{ width: 120 }}
              onChange={(e) => handChange(e, 'purpose')}
            >
              {params.purpose.map((item, index) => {
                return (
                  <Option value={item} key={index}>
                    {item}
                  </Option>
                );
              })}
            </Select>
          )}
        </Form.Item>
        <Form.Item name="staticts">
          {params.staticts && (
            <Select
              defaultValue={staticts || params.staticts[0]}
              style={{ width: 120 }}
              onChange={(e) => handChange(e, 'staticts')}
            >
              {params.staticts.map((item, index) => {
                return (
                  <Option value={item} key={index}>
                    {item}
                  </Option>
                );
              })}
            </Select>
          )}
        </Form.Item>
        {regionGeo && tabKey === regionAble ? (
          <Form.Item name="region">
            <TreeSelect
              style={{ width: '160px' }}
              treeNodeLabelProp="label"
              dropdownStyle={{ maxHeight: 400 }}
              treeData={regionGeo}
              placeholder="请选择"
              treeDefaultExpandAll
              onChange={(value, label) => handChange({ value, label }, 'region')}
              defaultValue={findTreeItem(regionGeo, region_code, 'value').label}
            />
          </Form.Item>
        ) : null}
        {/* 以tabkey为判断依据存在tabkey改变延迟导致报错  分开渲染处理 */}
        {datePickRender()}
        {dateRange && tabKey !== '4' && tabKey !== '3' && needSwitch ? (
          <Form.Item className={styles.changePick}>
            <SwapOutlined onClick={handleChangePick} className={styles.changePickIcon}/>
          </Form.Item>
          ) : null 
        }
      </Form>
    </div>
  );
};

export default connect(({ user, houseCommon }) => ({
  currentUser: user.currentUser,
  houseCommon,
}))(HeaderFilter);
